import { crc32, hexToSingle } from './bluetooth.js'
import { stateArr,settingArr,settingFmArr, settingAllArr,setting4GArr,settingFkqArr,settingDdfArr } from './constant.js'
import { convertArr2Obj, deepClone } from './index.js'
/**
 * 球阀状态格式化
 * @param {Object} value
 */
export function states(value,startAddr)
{
	let attrs = deepClone(stateArr)
	if(value.length > 12){
		const dataStr = value.substr(8,value.length - 8)
		const dataArr = dataStr.replace(/(.{4})(?=.)/g, "$1 ").split(' ')
		attrs.forEach((val,index) => {
			const currentIdx = val.addr - startAddr
			const len = val.len || 1
			const type = val.type || 'int'
			let res = ''
			for(let i =0;i<len;i++){
				res += dataArr[currentIdx+i]
			}
			val.value = parseInt(`0x${res}`)
			if(type === 'float'){
				val.value = hexToSingle(res)
			}
		})
	}
	return attrs
}

export function setting(value,idx,startAddr)
{
	let arr = []
	switch(idx){
		case 2:{
			arr = settingFmArr
		}
		break
		case 3:{
			arr = settingArr
		}
		break
		case 4:{
			arr = settingAllArr
		}
		break
		case 5:{
			arr = setting4GArr
		}
		break
		case 6:{
			arr = settingFkqArr
		}
		break
		case 7:{
			arr = settingDdfArr
		}
		break
	}

	let attrs = deepClone(arr)
	attrs = attrs.filter((val) => {
		return val.stateIdx !== undefined
	})
	if(value.length > 12){
		const dataStr = value.substr(8,value.length - 8)
		const dataArr = dataStr.replace(/(.{4})(?=.)/g, "$1 ").split(' ')
		attrs.forEach((val,index) => {
			const currentIdx = val.addr - startAddr
			const len = val.len || 1
			val.value = getStates(dataStr,startAddr,val.addr,len,val.dataType,val)
			if(val.addr === 0){
				val.valueText = getDeviceType(dataStr)
			}
			if(val.enums.length > 1){
				const enums = val.enums
				const enumsObj = convertArr2Obj(enums,'params')
				if(enumsObj && enumsObj[val.value]){
					val.valueText = enumsObj[val.value].name || ''
				}
			}
			if(val.addr === 4567){
				const lng = dataArr[4] + dataArr[5]
				const lat = dataArr[6] + dataArr[7]
				val.value = parseInt(`0x${lng}`)/1000000 + ',' + parseInt(`0x${lat}`)/1000000
			}
		})
	}
	return attrs
}

export function getDeviceType(dataStr){
	const dataArr = dataStr.replace(/(.{2})(?=.)/g, "$1 ").split(' ')
	const deviceTypeMap = {
		'00':'2口球阀',
		49:'4口球阀',
		46:'2口球阀',
		47:'脉冲阀控',
		48:'电动阀'
	}
	const deviceCodeMap = {
		'00':'LoRa',
		'01':'4G',
		'46':'LoRa'
	}
	const deviceType = deviceTypeMap[dataArr[0]] || ''
	const deviceCode = deviceCodeMap[dataArr[1]] || ''
	if(deviceType && deviceCode){
		return [deviceType,deviceCode].join(' - ')
	}
	return '未知设备'
}

/**
 * 生成控制指令
 * @param {Object} addr
 * @param {Object} value
 */
export function command(addr,value,code = '06',len=1){
	const str = 'ff' + code + addr.toString(16).padStart(4,0) + (+value).toString(16).padStart(4*len,0)
	const crc = crc32(str).toLowerCase()
	return str + crc
}

/**
 * 生成控制指令(值原样输入)
 * @param {Object} addr
 * @param {Object} value
 */
export function commandRaw(addr,value,code = '06'){
	const str = 'FF' + code + addr.toString(16).padStart(4,0) + value
	const crc = crc32(str)
	return str + crc
}

/**
 * 生成控制指令（值为char类型）
 * @param {Object} addr
 * @param {Object} value
 */
export function commandForChar(addr,value,code = '06',len = 1){
	
	const valueAscii = getAsciiCodes(value)
	const regLength = (valueAscii.length/4).toString(16).padStart(4,0)
	const byteLength = (valueAscii.length/2).toString(16).padStart(2,0)
	const str = 'ff' + code + addr.toString(16).padStart(4,0) + regLength + byteLength + getAsciiCodes(value)
	const crc = crc32(str).toLowerCase()
	return str + crc
}

/**
 * 根据传来的字符串生成对应ASCII码
 * @param {Object} str
 */
export function getAsciiCodes(str)
{
	let append = ''
	if(str.length%2 > 0){
		append = '00'
	}
	const length = str.length;
	
	let arr = [];
	for(let i=0;i<length;i++)
	{
		if(str[i].charCodeAt() < 127 && str[i].charCodeAt() > 32){
			arr.push(str[i].charCodeAt().toString(16).padStart(2,0))
		} else {
			throw new Error('提交的数据中有非法字符')
		}
	}
	return arr.join('') + append;
}

/**
 * 根据返回的值进行解析
 * @param {Object} value
 * @param {Object} startAddr
 * @param {Object} addr
 * @param {Object} len
 * @param {Object} dataType
 */
export function getStates(value,startAddr,addr,len,dataType,val)
{
	const dataStr = value.substr(4*(addr-startAddr),len*4)
	console.log(dataStr)
	let dataArr = []
	if(dataType === 'char'){
		dataArr = dataStr.replace(/(.{2})(?=.)/g, "$1 ").split(' ')
		dataArr = dataArr.filter((val) => {
			return val !== '00'
		})
		let str = ''
		dataArr.forEach((item) => {
			str += String.fromCharCode(parseInt(`0x${item}`))
		})
		return str
	} else {
		const res = parseInt(`0x${dataStr}`)
		// if(val.enums && val.enums.length > 0){
		// 	const valObj = convertArr2Obj(val.enums,'params')
		// 	return (valObj[res] && valObj[res]['name']) || ''
		// }
		return res
	}
}
